import traceback
from django.http import HttpResponse

from .forms import SaveFileForm
from .check_idcard import check_idcard_img
import datetime
import os
from pathlib import Path
import json

import requests
import uuid
# Create your views here.

BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_ROOT = os.path.join(BASE_DIR,'IDCardOCR')
IDCardOCR_MEDIA_ROOT = os.path.join(PROJECT_ROOT,'imgs')


def recognize_idcard(request):
    if request.method == 'POST':
        form = SaveFileForm(request.POST, request.FILES)

        if form.is_valid():
            files = request.FILES.getlist('file')
            file_url = form.cleaned_data['fileUrl']
            fid = "%s" % uuid.uuid4()
            resource_file_name = fid
            if len(files) > 0:
                resource_file_name = files[0].name
            if len(file_url.split("/")) > 1:
                resource_file_name = file_url.split("/")[len(file_url.split("/"))-1]
            if resource_file_name == fid:
                return HttpResponse("请上传图片")

            filename = datetime.datetime.strftime(datetime.date.today(), '%Y-%m-%d') + '-' + fid + '-' + resource_file_name
            filename_ret = datetime.datetime.strftime(datetime.date.today(), '%Y-%m-%d') + '-' + fid + '-ret-' + resource_file_name
            filename_err = datetime.datetime.strftime(datetime.date.today(), '%Y-%m-%d') + '-' + fid + '-err-' + resource_file_name
            filepath = os.path.join(IDCardOCR_MEDIA_ROOT, filename)
            fileretpath = os.path.join(IDCardOCR_MEDIA_ROOT, filename_ret)
            fileerrpath = os.path.join(IDCardOCR_MEDIA_ROOT, filename_err)

            # 传的链接
            if len(file_url)>0:
                r = requests.get(file_url)
                with open(filepath, "wb") as code:
                    code.write(r.content)

            # 直接传图
            if len(files) > 0:
                # save_file = SaveFileModel()
                # save_file.save()
                destination = open(filepath, 'wb+')
                if len(files) > 0:
                    for chunk in files[0].chunks():
                        destination.write(chunk)
                    destination.close()

            try:
                idcard,ret_img = check_idcard_img(filepath, debug=request.GET.__contains__('debug'))
                ret_img.save(fileretpath)
                idcard.check_uid = fid
                idcard_str = json.dumps(idcard.to_dict(),ensure_ascii=False)
                if request.GET.__contains__('debug'):
                    return HttpResponse(idcard_str + "," + "/IDCardOCR/imgs/" + filename_ret)
                return HttpResponse(idcard_str)
            except Exception as e:
                if len(file_url) > 0:
                    with open(fileerrpath, "wb") as code:
                        code.write(r.content)
                if len(files) > 0:
                    destination = open(fileerrpath, 'wb+')
                    for chunk in files[0].chunks():
                        destination.write(chunk)
                    destination.close()
                print(e)
                traceback.print_exc()
                if len(e.args)>0:
                    return HttpResponse("图片验证失败,报错,"+e.args[0])
                return HttpResponse("图片验证失败,报错,")
        return HttpResponse(form.errors)
    else:
        return HttpResponse("使用POST - form-data调用")
